<?php
/*
 * emarket - a website to create your own online-shop.  
 * Copyright (C) 2009  Frédéric Delorme
 *
 * This file is part of emarket.
 *
 * emarket is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * emarket is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with emarket.  If not, see <http://www.gnu.org/licenses/>.
 *
 * To contact me: frederic.delorme@gmail.com
 * to see some information on te project : http://code.google.col/p/os-emarket/
 *
 */
global $framework;
require_once("../entities/user.php");
require_once("$framework/session.php");
/**
 * Authenticate user with HTTP system.
 * @author delormef
 *
 */
class Autenticate{
	/**
	 * Request an authentication to the server.
	 * @param $realm
	 * @return unknown_type
	 */
	function login($realm="Basic Authentication") {
		header('WWW-Authenticate: Basic realm="$realm"');
		header("HTTP/1.0 401 Unauthorized");
		exit;
	}
	
	/**
	 * Verify if a user is connected. if not, send a Server Authentication request.
	 * @param $userManager
	 * @return unknown_type
	 */
	function verify($userManager){
		$user=array();
		$fieldCountAttemptLogin = __sysparam('user','fieldCountAttemptLogin');
		if (! isset($_SERVER['PHP_AUTH_USER'])) {
			login();
		} else {
			
			$user = $userManager->retrieve($_SERVER['PHP_AUTH_USER']);
			if(!empty($user)){
				if ($user['password']==$_SERVER['PHP_AUTH_PW']){
					Session::set("userConnected",$user);
				}else{
					$user[$fieldCountAttemptLogin]+=1;
					$userManager->update($user);
					Authenticate::login();
				}
			}else{
				Authenticate::login();
			}
		}	
	}
}
?>